<?php
require_once 'database.php';

class Mysql extends  Database {
	private $openlog = false;
	private $ispconnect = false;

	public function connect($pconnect = false) {
		$this->link = (($pconnect) ? mysql_pconnect($this->host, $this->username, $this->password) :
									 mysql_connect($this->host, $this->username, $this->password));
		if( !$this->link ) {
			return false;
		}
		$ispconnect = $pconnect;
		mysql_select_db($this->dbname);
		mysql_query("SET NAMES 'utf8'");
		return true;
	}
	
	public function quoteInfo($sql) {
		return mysql_real_escape_string($sql);
	}

	public function query($sql) {
		if( $this->debug ) {
			$this->lastSql = $sql;
		}
		
		$res = mysql_query($sql);
		if($res == null) {
			$this->log("$sql syntax error");
			exit(":DB ERROR");
		}
		if($res == false) {
			$this->log("$sql excute failed");
			exit(":DB ERROR");
		}
		return $res;
	}

	public function close() {
		if($this->link != null) {
			mysql_close();
			$this->link = null;
		}
	}

	protected function log($str) {
		if($this->openlog) {
			file_put_contents("err_log.txt", $str, FILE_APPEND);
		} else {
			echo $str;
		}
	}

	public function setlog($open) {
		$this->openlog = $open;
	}

	public function fetch_array($cid) {
		return mysql_fetch_array($cid);
	}

	public function num_rows($cid) {
		return mysql_num_rows($cid);
	}

	public function affected_rows() {
		return mysql_affected_rows($this->link);
	}

	public function insertId() {
		return mysql_insert_id($this->link);
	}

	public function fetchAll($sql) {
		$res = $this->query($sql);
		if($res == null)	return null;
			
		$data = array();
		for($i = 0; $tempRow = $this->fetch_array($res); $i++) {
			$data[$i] = $tempRow;
		}
		return $data;
	}

	public function assoc_array($cid) {
		return mysql_fetch_assoc($cid);
	}

	public function assocAll($sql) {
		$res = $this->query($sql);
		if($res == null)	return null;

		$data = array();
		for($i = 0; $tempRow = $this->assoc_array($res); $i++) {
			$data[$i] = $tempRow;
		}
		return $data;
	}
}